//
//  FriendsViewController.m
//  Guazi
//
//  Created by koolearn on 11-5-25.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "FriendsViewController.h"
#import "TwitterClient.h"
#import "FriendGroup.h"
#import "ABContact.h"
#import "ABContactsHelper.h"
#import "User.h"
#import "GuaziAppDelegate.h"
#import "TwitterClient.h"
#import "GroupHeaderView.h"
#import "ContactCell.h"
#import "GroupToolbarCell.h"
#import "ContactDetailViewController.h"
#import "ColorUtils.h"
#import "PopMenuViewController.h"
#import "GroupAddViewController.h"
#import "NetworkUtil.h"
#import "GroupService.h"
#import "NewContactViewController.h"
#import "RegisterViewController.h"
#import "StringUtil.h"
#import "NoContactCell.h"
#import "SearchPhoneCell.h"
#import "OperationLog.h"
#import "DataUploadService.h"
#import "REString.h"
#import "FriendDetailViewController.h"


@interface FriendsViewController(private)
- (NSArray*) loadLocalContacts;

- (NSArray*) loadFrequentContacts;
- (void) loadContactForGroup:(FriendGroup*)group continueNextGroup:(BOOL)b force:(BOOL)force;
- (void) didLoadContactForGroup:(id)sender obj:(NSObject*)obj;
- (void) fillUsers;
- (void) loadData;
- (void) sortGroupFriends;

- (void) expandSection:(NSInteger)section group:(FriendGroup*)group;
- (void) collapseSecton:(NSInteger)section group:(FriendGroup*)group;

- (void) reloadGroup:(sqlite3_int64)groupId;
- (void) refreshToolbarCell:(sqlite3_int64)groupId;

- (CGFloat) getCellHeight:(NSIndexPath*)indexPath;

- (FriendGroup*) findGroupInArr:(NSArray*)array groupId:(sqlite3_int64)groupId;
- (User*) findUserInArr:(NSArray*)array userId:(sqlite3_int64)userId;
- (FriendGroup*) findExpandedGroup;

- (void) addFriends:(NSArray*)friends toGroup:(FriendGroup*)group;

- (void) addGroup;
- (void) newContact;
- (void) updateGroups:(NSArray*)groups;
- (void) deleteGroups:(NSArray*)groups;

- (FriendGroup*) groupForSection:(NSInteger)section;
- (NSInteger) sectionForGroup:(sqlite_int64)groupId;

- (NSString*) getSearcharText;
- (BOOL) isSearching;
- (void) buildBarButtonItems;

-(void)displaySMSComposerSheet:(NSArray*)recipients body:(NSString*)body;
-(void) send:(NSArray*)recipients body:(NSString*)body;

@end


@implementation FriendsViewController

@synthesize groups;
@synthesize allUsers;
@synthesize filterUsers;
@synthesize popoverController;
@synthesize searchBar;
@synthesize isLoaded;


- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        self.isLoaded = NO;
    }
    return self;
}



- (void)dealloc
{
    [groups release];
	[popoverController release];
    [operationQueue release];
    [searchBar release];
    [filterUsers release];
    [allUsers release];
    [super dealloc];
}



- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}




#pragma mark - 处理本地缓存数据及本地通讯录

- (NSMutableArray*) loadLocalData
{
    //得到本地缓存的数据
    //NSMutableArray* localGroups = (NSMutableArray*) [FriendGroup loadGroupsAndUsers];
    NSMutableArray* localGroups = (NSMutableArray*) [FriendGroup loadGroups:YES onlyRealGroup:NO];
    
    FriendGroup* group = [self findGroupInArr:localGroups groupId:-1];
    if ( group == nil ) {
        group = [self findGroupInArr:localGroups groupId:-1];
        group = [FriendGroup groupWithId:-1 name:@"常用联系人"];
        [group updateDB];
        [localGroups insertObject:group atIndex:0];
    }
    
    group = [self findGroupInArr:localGroups groupId:0];
    if ( group == nil ) {
        group = [FriendGroup groupWithId:0 name:@"未分组"];
        [group updateDB];
        [localGroups addObject:group];
    }
    
    return localGroups;
}


- (void) processLocalContacts
{
    NSArray* localContacts = [self loadLocalContacts];
    if ( [localContacts count] == 0 ) return;
    
    NSMutableDictionary* dic = [NSMutableDictionary dictionaryWithCapacity:[allUsers count]];
    for ( User* user in allUsers ) {
        [dic setObject:user forKey:user.phone];
    }
    
    FriendGroup* group = [self findGroupInArr:groups groupId:0];
    
    for ( User* user in localContacts ) {
        if ( [dic objectForKey:user.phone] == nil ) {
            [user updateDB:YES withName:YES withAccount:NO];
            [FriendGroup insertGroupUser:user.userId groupId:0 seq:0];
            [group.friends insertObject:user atIndex:0];
            
            OperationLog* log = [[OperationLog alloc] initWithModule:kOperationLogModulePerson 
                                                           operation:kOperationLogOperationAdd 
                                                               refId:[NSString stringWithFormat:@"%lld", user.userId] 
                                                              params:[user toJsonString]];
            [log insert];
            [log release];
        }
    }
    
    [[DataUploadService sharedInstance] run];
}


- (NSArray*) loadLocalContacts
{
	NSArray* contacts = [ABContactsHelper contacts];
	NSMutableArray* users = [NSMutableArray arrayWithCapacity:[contacts count]];
	
	User* user = nil;
	for ( ABContact* contact in contacts ) {
		user = [[User alloc] initWithABContact:contact];
		[users addObject:user];
		[user release];
	}
	return users;
}



#pragma mark - 与服务器的同步操作


- (void) registerPhone
{
    if ( [kUserStateValid compare:[GuaziAppDelegate getAppDelegate].user.state] == NSOrderedSame ) {
        [[DataUploadService sharedInstance] run:0];
    }
    else {
        [GuaziAppDelegate openRegisterView:self];
    }
    
    //RegisterViewController* controller = [[RegisterViewController alloc] initWithStyle:UITableViewStyleGrouped];
    //UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:controller];
    //nav.hidesBottomBarWhenPushed = YES;
    //[self.navigationController presentModalViewController:nav animated:YES];
    
    //controller.hidesBottomBarWhenPushed = YES;
    //[self.navigationController pushViewController:controller animated:YES];
}


/* 从服务器上同步分组数据 */
- (void) syncGroupsFromServer
{
    NSArray* groupList = [TwitterClient getGroups];
    
    NSMutableArray* deletedGroups = [NSMutableArray array];
    for ( FriendGroup* currGroup in groups ) {
        if ( currGroup.groupId < 0 ) continue;
        
        FriendGroup* group = [self findGroupInArr:groupList groupId:currGroup.groupId];
        if ( group ) {
            group.friends = currGroup.friends;
            group.restored = currGroup.restored;
            group.loaded = currGroup.loaded;
        }
        else {
            [deletedGroups addObject:currGroup];
        }
    }
    
    if ( [deletedGroups count] > 0 ) {
        [self deleteGroups:deletedGroups];
    }
   
    FriendGroup* group = [self findGroupInArr:groups groupId:-1];
    if ( group == nil ) {
        group = [FriendGroup groupWithId:-1 name:@"常用联系人"];
    }
    
    [groups removeAllObjects];
    [groups addObject:group];
    for ( FriendGroup* group in groupList ) {
        [groups addObject:group];
    }
    
    [self updateGroups:groups];
}



- (void) syncUsersFromServer
{
    FriendGroup* group = [groups objectAtIndex:0];
    [self loadContactForGroup:group continueNextGroup:YES force:NO];
}


//异步加载分组下的联系人
- (void) loadContactForGroup:(FriendGroup*)group continueNextGroup:(BOOL)b force:(BOOL)force
{
    NSLog(@"begin load user for group:%lld, %@", group.groupId, group.name);
	if ( !force && group.loaded ) return;
	if ( client ) return;
    
    group.loading = YES;
	
	SEL action = nil;
	if ( b ) {
		action = @selector(didLoadContactForGroupContinue:obj:);
	}
	else {
		action = @selector(didLoadContactForGroup:obj:);
	}
	
	client = [[TwitterClient alloc] initWithTarget:self action:action];
	client.context = group;
    
    if ( group.groupId == -1 ) {
        [client getFriendsByUserId:[GuaziAppDelegate getAppDelegate].user.userId page:0 rows:10 orderby:0 isFollowers:NO];
    }
    else {
        [client getUsersInGroup:group.groupId];
    }
}


//异步加载分组下的联系人。本分组加载完成后，在加载下一个分组的联系人
- (void) didLoadContactForGroupContinue:(id)sender obj:(NSObject *)obj
{
	client = nil;
	TwitterClient* twitterClient = (TwitterClient*) sender;
	FriendGroup* group = (FriendGroup*) twitterClient.context;
	
    NSLog(@"did load user for group:%lld, %@", group.groupId, group.name);
	[self didLoadContactForGroup:sender obj:obj];
	
	int index = -1;
	for ( int i=0; i<[groups count]; i++ ) {
		FriendGroup* g = [groups objectAtIndex:i];
		if ( g.groupId == group.groupId ) {
			index = i;
			break;
		}
	}
	
	if ( index < [groups count] - 1 ) {
		index++;
		group = [groups objectAtIndex:index];
        [self loadContactForGroup:group continueNextGroup:YES force:NO];
	}
}


//异步加载分组下的联系人
- (void) didLoadContactForGroup:(id)sender obj:(NSObject*)obj
{
	client = nil;
	TwitterClient* twitterClient = (TwitterClient*) sender;
	
    FriendGroup* group = (FriendGroup*) twitterClient.context;
    group.loading = NO;
	
	if ( twitterClient.hasError ) {
		[twitterClient alert];
		return;
	}

    if ( obj == nil ) return;
    
    NSMutableDictionary* dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%lld", group.groupId], @"groupId", obj, @"result", nil];
    NSInvocationOperation* operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(updateContactsForGroup:) object:dic];
    [operationQueue addOperation:operation];
    [operation release];
}


- (void)updateContactsForGroup:(NSDictionary*)data
{
    if ( !data ) return;

    long long groupId = [((NSString*) [data objectForKey:@"groupId"]) longLongValue];
    FriendGroup* group = [self findGroupInArr:groups groupId:groupId];
    if ( group == nil ) return;
    
    id obj = [data objectForKey:@"result"];
    if ( obj == nil ) return;
    
    NSArray* arr = nil;
    if ( groupId == -1 ) {
        if ( ![obj isKindOfClass:[NSArray class]] ) return;
        arr = (NSArray*) obj;
    }
    else {
        if ( ![obj isKindOfClass:[NSDictionary class]] ) return;
        NSDictionary* dic = (NSDictionary*) obj;
        arr = [dic objectForKey:@"friends"];
    }
    
    if ( arr == nil ) return;
    if ( (id)arr == [NSNull null] ) return;
    
    NSMutableArray* users = [NSMutableArray array];
    for ( int i=0; i<[arr count]; i++ ) {
        NSDictionary* userDic = [arr objectAtIndex:i];
        if ( userDic == nil || ![userDic isKindOfClass:[NSDictionary class]] ) continue;
        User* user = [[User alloc] initWithJsonDictionary:userDic];
        [users addObject:user];
        [user updateDB:YES withName:NO withAccount:NO];
        [user release];
        
        NSDictionary* tweetDic = [userDic objectForKey:@"lastest_weibo"];
        if ( tweetDic != nil && (id)tweetDic!=[NSNull null] && [userDic isKindOfClass:[NSDictionary class]]) {
            Status* status = [Status statusWithJsonDictionary:tweetDic type:TWEET_TYPE_FRIENDS];
            status.user = user;
            [status insertDB:@"contact_statuses"];
            user.status = status;
        }
    }
    
    
	//更新group下的人员
    if ( users && [users count] > 0 ) {
        [users sortUsingFunction:sortByScreenName context:nil];
    }

	group.friends = users;
	group.loaded = YES;
    
	if ( group.expanded || group.groupId == -1 ) {
		[self.tableView reloadData];
	}
    
	//更新数据库
	[FriendGroup setUsers:users groupId:group.groupId];
}



#pragma mark -
#pragma mark 选中分组的操作

//选中某个分组
- (void) sectionDidSelected:(NSInteger)section
{
	FriendGroup* group = [self groupForSection:section];
    if ( !group ) return;
    
    if ( group.expanded ) {
        [self collapseSecton:section group:group];
    }
    else {
        for ( int i=0; i<[groups count]; i++ ) {
            FriendGroup* g = [groups objectAtIndex:i];
            if ( g.expanded ) {
                NSInteger sectionIndex = [self sectionForGroup:g.groupId];
                [self collapseSecton:sectionIndex group:g];
            }
        }
        
        [self expandSection:section group:group];
    }
    
	[self.tableView reloadData];
}


- (void) expandSection:(NSInteger)section group:(FriendGroup*)group
{
	if ( group.expanded ) return;
	group.expanded = YES;
	
	/*NSArray* users = group.friends;
	NSMutableArray* insertRows = [NSMutableArray arrayWithCapacity:[users count]];
	
	[self.tableView beginUpdates];
	for ( int i=0; i<[users count]; i++ ) {
		NSIndexPath* indexPath = [NSIndexPath indexPathForRow:i inSection:section];
		[insertRows addObject:indexPath];
	}
	
	[self.tableView insertRowsAtIndexPaths:insertRows withRowAnimation:UITableViewRowAnimationNone];
	[self.tableView endUpdates];*/
}


- (void) collapseSecton:(NSInteger)section group:(FriendGroup*)group
{
	if ( !group.expanded ) return;
	group.expanded = NO;
	
    /*
	NSArray* users = group.friends;
	NSMutableArray* deleteRows = [NSMutableArray arrayWithCapacity:[users count]];
	
	[self.tableView beginUpdates];
	for ( int i=0; i<[users count]; i++ ) {
		NSIndexPath* indexPath = [NSIndexPath indexPathForRow:i inSection:section];
		[deleteRows addObject:indexPath];
	}
	
	[self.tableView deleteRowsAtIndexPaths:deleteRows withRowAnimation:UITableViewRowAnimationMiddle];
	[self.tableView endUpdates];
     */
	
	//[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationNone];
}



#pragma mark - refresh operations

- (void) refreshTableView
{
    self.searchBar.text = @"";
    [self buildBarButtonItems];
    [self.tableView reloadData];
}


- (void) refreshGroup:(FriendGroup*)group
{
    FriendGroup* g = [self findGroupInArr:groups groupId:group.groupId];
    if ( g ) {
        g.name = group.name;
        g.isPublic = group.isPublic;
    }
    [self.tableView reloadData];
}


- (void) refreshAddGroup:(FriendGroup*)group
{
    group.friendCount = 0;
    group.friends = [NSMutableArray arrayWithCapacity:0];
    
    NSInteger index = 0;
    for ( int i=0; i<[groups count]; i++ ) {
        FriendGroup* g = [groups objectAtIndex:i];
        if ( g.groupId > 0 ) {
            index = i;
            break;
        }
    }
    [groups insertObject:group atIndex:index];
    [self.tableView reloadData];
}


- (void) refreshDeleteGroup:(FriendGroup*)group
{
    FriendGroup* g = [self findGroupInArr:groups groupId:group.groupId];
    if ( g ) {
        [self.groups removeObject:g];
        NSArray* friends = group.friends;
        if ( [friends count] > 0 ) {
            FriendGroup* ungroup = [self findGroupInArr:groups groupId:0];
            if ( !ungroup ) {
                ungroup = [FriendGroup groupWithId:0 name:@"未分组"];
                ungroup.friends = group.friends;
                ungroup.friendCount = [group.friends count];
                ungroup.restored = YES;
                ungroup.loaded = YES;
                [groups addObject:ungroup];
            }
            else {
                [self addFriends:friends toGroup:ungroup];
            }
        }
        [self.tableView reloadData];
    }
}


- (void) refreshUsersInGroup:(FriendGroup*)group
{
    FriendGroup* g = [self findGroupInArr:groups groupId:group.groupId];
    if ( g ) {
        g.friends = group.friends;
        g.friendCount = [group.friends count];
    }
    [self.tableView reloadData];
}


//设置用户分组后刷新
- (void) refreshSetUserGroup:(User*)user oldGroups:(NSArray*)oldGroups newGroups:(NSArray*)newGroups
{
    if ( [oldGroups count] == 0 ) {
        //从未分组中移除
        FriendGroup* group = [self findGroupInArr:groups groupId:0];
        if ( group ) {
            User* u = [self findUserInArr:group.friends userId:user.userId];
            if ( u ) {
                [group.friends removeObject:u];
            }
        }
    }
    else {
        for ( NSString* s in oldGroups ) {
            FriendGroup* group = [self findGroupInArr:groups groupId:[s longLongValue]];
            if ( group ) {
                User* u = [self findUserInArr:group.friends userId:user.userId];
                if ( u ) {
                    [group.friends removeObject:u];
                }
            }
        }
    }
    
    if ( [newGroups count] == 0 ) {
        //增加到未分组中
        FriendGroup* group = [self findGroupInArr:groups groupId:0];
        if ( group ) {
            User* u = [self findUserInArr:group.friends userId:user.userId];
            if ( !u ) {
                [group.friends insertObject:user atIndex:0];
            }
        }
    }
    else {
        //增加到其他分组中
        for ( NSString* s in newGroups ) {
            FriendGroup* group = [self findGroupInArr:groups groupId:[s longLongValue]];
            if ( group ) {
                User* u = [self findUserInArr:group.friends userId:user.userId];
                if ( !u ) {
                    [group.friends insertObject:user atIndex:0];
                }
            }
        }
    }
    
    [self.tableView reloadData];
}


- (void) refreshDestroyFriendship:(sqlite3_int64)userId
{
    NSArray* gs = [FriendGroup getGroupsWithUserId:userId];
    if ( [gs count] == 0 ) {
        //从未分组中移除
        FriendGroup* group = [self findGroupInArr:groups groupId:0];
        if ( group ) {
            User* u = [self findUserInArr:group.friends userId:userId];
            if ( u ) {
                [group.friends removeObject:u];
            }
        }
    }
    else {
        //从分组中移除
        for ( FriendGroup* g in gs ) {
            FriendGroup* group = [self findGroupInArr:groups groupId:g.groupId];
            User* u = [self findUserInArr:group.friends userId:userId];
            if ( u ) {
                [group.friends removeObject:u];
            }
        }
    }
    
    //从常用联系人中移除
    FriendGroup* group = [self findGroupInArr:groups groupId:-1];
    if ( group ) {
        User* u = [self findUserInArr:group.friends userId:userId];
        if ( u ) {
            [group.friends removeObject:u];
        }
    }
    
    [self.tableView reloadData];
}


- (void) refreshCreateFriendship:(User*)user 
{
    NSArray* gs = [FriendGroup getGroupsWithUserId:user.userId];
    if ( [gs count] == 0 ) {
        //增加到未分组
        FriendGroup* group = [self findGroupInArr:groups groupId:0];
        User* u = [self findUserInArr:group.friends userId:user.userId];
        if ( !u ) {
            [group.friends insertObject:user atIndex:0];
        }
    }
    else {
        for ( FriendGroup* g in gs ) {
            FriendGroup* group = [self findGroupInArr:groups groupId:g.groupId];
            if ( group ) {
                User* u = [self findUserInArr:group.friends userId:user.userId];
                if ( !u ) {
                    [group.friends insertObject:user atIndex:0];
                }
            }
        }
    }
    
    [self.tableView reloadData];
}


- (void) refreshUsersInGroup:(FriendGroup*)group toUsers:(NSArray*)toUsers
{
    NSMutableArray* deletedUsers = [[NSMutableArray alloc] init];
    NSMutableArray* addedIndexPathes = [[NSMutableArray alloc] init];
    NSMutableArray* deletedIndexPathes = [[NSMutableArray alloc] init];
    
    NSInteger section = [self sectionForGroup:group.groupId];
    group.friendCount = [toUsers count];
    NSMutableArray* fromUsers = group.friends;
    
    NSMutableDictionary* toUserDic = [[NSMutableDictionary alloc] initWithCapacity:[toUsers count]];
    for ( User* user in toUsers ) {
        [toUserDic setObject:user forKey:[NSNumber numberWithLongLong:user.userId]];
    }
    
    for ( int i=0; i<[fromUsers count]; i++ ) {
        User* fromUser = [fromUsers objectAtIndex:i];
        User* toUser = [toUserDic objectForKey:[NSNumber numberWithLongLong:fromUser.userId]];
        if ( !toUser ) {
            [deletedUsers addObject:fromUser];
            [deletedIndexPathes addObject:[NSIndexPath indexPathForRow:i inSection:section]];
        }
    }
    
    if ( [deletedUsers count] > 0 ) {
        for ( User* u in deletedUsers ) {
            [fromUsers removeObject:u];
        }
        
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:deletedIndexPathes withRowAnimation:UITableViewRowAnimationNone];
        [self.tableView endUpdates];
    }
    
    [deletedIndexPathes release];
    [deletedUsers release];
    [toUserDic release];
    
    NSMutableDictionary* fromUserDic = [[NSMutableDictionary alloc] initWithCapacity:[fromUsers count]];
    for ( User* user in fromUsers ) {
        [fromUserDic setObject:user forKey:[NSNumber numberWithLongLong:user.userId]];
    }

    for ( int i=0; i<[toUsers count]; i++ ) {
        User* toUser = [toUsers objectAtIndex:i];
        User* fromUser = [fromUserDic objectForKey:[NSNumber numberWithLongLong:toUser.userId]];
        if ( !fromUser ) {
            [fromUsers insertObject:toUser atIndex:i];
            [addedIndexPathes addObject:[NSIndexPath indexPathForRow:i inSection:section]];
        }
    }
    
    if ( [addedIndexPathes count] > 0 ) {
        [self.tableView beginUpdates];
        [self.tableView insertRowsAtIndexPaths:addedIndexPathes withRowAnimation:UITableViewRowAnimationNone];
        [self.tableView endUpdates];
    }
    
    [addedIndexPathes release];
    [fromUserDic release];
}


- (void) reloadGroup:(sqlite3_int64)groupId
{
    int i = [self sectionForGroup:groupId];
    if ( i>=0 ) {
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:i] withRowAnimation:UITableViewRowAnimationFade];
    }
}


- (void) refreshSwitchUser
{
    [self loadData];
    [self.tableView reloadData];
}


#pragma mark - tools methods

//判断是否注册了
- (BOOL) isRegistered
{
	User* user = [GuaziAppDelegate getAppDelegate].user;
	if ( user != nil ) return YES;
	return NO;
}


- (FriendGroup*) findGroupInArr:(NSArray*)array groupId:(sqlite3_int64)groupId
{
    if ( !array ) return nil;
    if ( [array count] == 0 ) return nil;
    
    for ( FriendGroup* group in array ) {
        if ( group.groupId == groupId ) {
            return group;
        }
    }
    
    return nil;
}


- (User*) findUserInArr:(NSArray*)array userId:(sqlite3_int64)userId
{
    if ( !array ) return nil;
    if ( [array count] == 0 ) return nil;
    
    for ( User* user in array ) {
        if ( user.userId == userId ) {
            return user;
        }
    }
    
    return nil;
}


- (FriendGroup*) findExpandedGroup
{
    for ( FriendGroup* group in groups ) {
        if ( group.expanded ) return group;
    }
    return nil;
}


- (void) updateGroups:(NSArray*)groupList
{
    if ( !groupList || [groupList count] == 0 ) return;
    
    for ( FriendGroup* group in groupList ) {
        [group updateDB];
    }
}


- (void) deleteGroups:(NSArray*)groupList
{
    if ( !groupList || [groupList count] == 0 ) return;
    
    for ( FriendGroup* group in groupList ) {
        [GroupService deleteGroup:group.groupId];
    }
    
}


- (void) addFriends:(NSArray*)friends toGroup:(FriendGroup*)group
{
    if ( !friends ) return;
    if ( [friends count] == 0 ) return;
    
    NSMutableArray* groupFriends = group.friends;
    NSMutableDictionary* dic = [[NSMutableDictionary alloc] initWithCapacity:[friends count]];
    for ( User* user in groupFriends ) {
        [dic setObject:user forKey:[NSNumber numberWithLongLong:user.userId]];
    }
    [dic release];
    
    int count = 0;
    for ( User* user in friends ) {
        User* u = [dic objectForKey:[NSNumber numberWithLongLong:user.userId]];
        if ( !u ) {
            [groupFriends insertObject:user atIndex:count];
            count++;
        }
    }
    
    group.friendCount = [groupFriends count];
}


- (void) fillUsers
{
    NSMutableDictionary* dic = [NSMutableDictionary dictionary];
    
    for ( FriendGroup* group in self.groups ) {
        for ( User* user in group.friends ) {
            [dic setObject:user forKey:[NSString stringWithFormat:@"%lld", user.userId]];
        }
    }
    
    self.allUsers = [dic allValues];

    if ( [self isSearching] ) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"remarkName contains[cd] %@ or user.name contains[cd] %@", [self getSearcharText]];
        self.filterUsers = [allUsers filteredArrayUsingPredicate:predicate];
    }
    
}


//打电话
- (void) callPhone:(NSString*)phoneNumber
{
	NSString* url = [NSString stringWithFormat:@"tel://%@", phoneNumber];
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}


//发短信
- (void) sendMessage:(NSString*)phoneNumber
{
    NSArray* array = [NSArray arrayWithObject:phoneNumber];
    NSString* message = @"";
    [self send:array body:message];
}


//增加联系人
- (void) addContact:(NSString*)text
{
    NewContactViewController* controller = [[NewContactViewController alloc] init];
    NSMutableArray* array = [NSMutableArray array];
    
    BOOL isPhone = NO;
    if ( [text matches:@"^[0-9]+" withSubstring:array] ) {
        if ( [array count] > 0 ) {
            isPhone = YES;
        }
    }
    
    if ( isPhone ) {
        controller.phone = text;
    }
    else {
        controller.contactName = text;
    }
    
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
}


#pragma mark - SMS operations

-(void) send:(NSArray*)recipients body:(NSString*)body
{
	Class messageClass = (NSClassFromString(@"MFMessageComposeViewController"));
	if (messageClass != nil) {
		// Check whether the current device is configured for sending SMS messages
		if ([messageClass canSendText]) {
			[self displaySMSComposerSheet:recipients body:body];
		}
		else {
			UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"设备没有短信功能" 
															message:@"您的设备不能发送短信" 
														   delegate:nil 
												  cancelButtonTitle:@"确定" 
												  otherButtonTitles:nil];
			[alert show];
			[alert release];
		}
	}
	else {
		UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"iOS版本过低" 
														message:@"iOS版本过低,iOS4.0以上才支持程序内发送短信" 
													   delegate:nil 
											  cancelButtonTitle:@"确定" 
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
}


-(void)displaySMSComposerSheet:(NSArray*)recipients body:(NSString*)body
{
	MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
	picker.messageComposeDelegate = self;
	picker.recipients = recipients;
	picker.body = body;
    picker.title = @"发送短信";
    
	[[[GuaziAppDelegate getAppDelegate] currentNavigationController] presentModalViewController:picker animated:YES];
	[picker release];
}


- (void)messageComposeViewController:(MFMessageComposeViewController *)messageComposeViewController
				 didFinishWithResult:(MessageComposeResult)result {
	switch (result)
	{
		case MessageComposeResultCancelled:
			NSLog(@"Result: SMS sending canceled");
			break;
		case MessageComposeResultSent:
			NSLog(@"Result: SMS sent");
			break;
		case MessageComposeResultFailed:
			NSLog(@"Result: sms fail");
			UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"短信发送失败" 
															message:@"短信发送失败" 
														   delegate:nil 
												  cancelButtonTitle:@"确定" 
												  otherButtonTitles:nil];
			[alert show];
			[alert release];
			break;
		default:
			NSLog(@"Result: SMS not sent");
			break;
	}
    
    [[[GuaziAppDelegate getAppDelegate] currentNavigationController] dismissModalViewControllerAnimated:YES];
}


#pragma mark - pop menu operations

- (void) showPopmenu:(id)sender
{
    [searchBar resignFirstResponder];
    
	if (!self.popoverController) {
		
		//UIViewController *contentViewController = [[WEPopoverContentViewController alloc] initWithStyle:UITableViewStylePlain];
		UIViewController* contentViewController = [[PopMenuViewController alloc] initWithContentDelegate:self];
		self.popoverController = [[[WEPopoverController alloc] initWithContentViewController:contentViewController] autorelease];
		self.popoverController.delegate = self;
		self.popoverController.passthroughViews = [NSArray arrayWithObject:self.navigationController.navigationBar];
		self.popoverController.view.backgroundColor = [UIColor blackColor];
		
		[self.popoverController presentPopoverFromBarButtonItem:sender 
									   permittedArrowDirections:(UIPopoverArrowDirectionUp|UIPopoverArrowDirectionDown) 
													   animated:YES];
		
		[contentViewController release];
	} 
    else {
		[self.popoverController dismissPopoverAnimated:YES];
		self.popoverController = nil;
	}

	
	/*
	if (self.popoverController) {
		[self.popoverController dismissPopoverAnimated:YES];
		self.popoverController = nil;
	} else {
		UIViewController *contentViewController = [[PopMenuViewController alloc] initWithMenuId:kPopMenuIdContacts];
		
		self.popoverController = [[[WEPopoverController alloc] initWithContentViewController:contentViewController] autorelease];
		[self.popoverController presentPopoverFromRect:self.navigationItem.rightBarButtonItem.customView.frame
												inView:self.view 
							  permittedArrowDirections:UIPopoverArrowDirectionDown
											  animated:YES];
		[contentViewController release];
	}*/
	
	
	/*
	WEPopoverTableViewController* controller = [[WEPopoverTableViewController alloc] initWithStyle:UITableViewStylePlain];
	[self.navigationController pushViewController:controller animated:YES];
	[controller release];
	 */
}


- (NSInteger) popMenuItemCount
{
    return 2;
}


- (NSString*) popMenuItemName:(NSInteger)menuItem
{
    if ( menuItem == 0 ) {
        return @"新建联系人";
    }
    else if ( menuItem == 1 ) {
        return @"新建分组";
    }
    else {
        return @"-";
    }
}


- (void) didSelectPopMenuItem:(NSInteger)menuItem
{
    [self.popoverController dismissPopoverAnimated:YES];
    self.popoverController = nil;
    
    selectedMenuItem = menuItem;
    if ( selectedMenuItem == 0 ) {
        [self newContact];
    }
    else if ( selectedMenuItem == 1 ) {
        [self addGroup];
    }
    else if ( selectedMenuItem == 2 ) {
        
    }
}


- (NSString*) popMenuTitle
{
    return @"新建操作";
}


#pragma mark -
#pragma mark WEPopoverControllerDelegate implementation

- (void)popoverControllerDidDismissPopover:(WEPopoverController *)thePopoverController {
	//Safe to release the popover here
	self.popoverController = nil;
    if ( selectedMenuItem == 0 ) {
        [self newContact];
    }
    else if ( selectedMenuItem == 1 ) {
        [self addGroup];
    }
    else if ( selectedMenuItem == 2 ) {
        
    }
}

- (BOOL)popoverControllerShouldDismissPopover:(WEPopoverController *)thePopoverController {
	//The popover is automatically dismissed if you click outside it, unless you return NO here
	return YES;
}


- (void) addGroup
{
	GroupAddViewController* controller = [[GroupAddViewController alloc] init];
    controller.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:controller action:@selector(saveInStackView)];
    
	[self.navigationController pushViewController:controller animated:YES];
	[controller release];
}


- (void) newContact
{
    NewContactViewController* controller = [[NewContactViewController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
}


#pragma mark - View lifecycle

- (void) buildBarButtonItems
{
    if ( [self isSearching] ) {
		self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"返回" 
																				 style:UIBarButtonItemStylePlain target:self action:@selector(refreshTableView)] autorelease];
    }
    else {
        self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh 
                                                                                               target:self action:@selector(registerPhone)] autorelease];
    }
    
    if ( ![self isSearching] || [filterUsers count] > 0 ) {
        self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd 
																						   target:self action:@selector(showPopmenu:)] autorelease];
    }
    else {
        self.navigationItem.rightBarButtonItem = nil;
    }
}


- (void) buildSearchBar
{
	// Create a search bar
	self.searchBar = [[[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 220.0f, 44.0f)] autorelease];
	searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
	searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
	searchBar.keyboardType = UIKeyboardTypeAlphabet;
	searchBar.placeholder = @"请输入名称或电话";
	searchBar.delegate = self;
	//searchBar.tintColor = [UIColor navigationColorForTab:0];
	
	self.navigationItem.titleView = searchBar;
	//self.tableView.tableHeaderView = searchBar;
}


- (void) loadData
{
    self.groups = [NSMutableArray array];
    
    operationQueue = [[NSOperationQueue alloc] init];
    [operationQueue setMaxConcurrentOperationCount:1];
    
    //得到本地缓存的数据
    NSMutableArray* localGroups = [self loadLocalData];
    self.groups = localGroups;
    [self fillUsers];
    
    //得到本地通讯录中的数据
    [self processLocalContacts];
    
    [self sortGroupFriends];
    //[self.tableView reloadData];
    
    BOOL networkAvailable = [NetworkUtil isbroadbandAvailable];
    networkAvailable = NO;

    //从服务器上同步分组数据
    if ( [[GuaziAppDelegate getAppDelegate] isAccountOpened] && networkAvailable ) {
        [self syncGroupsFromServer];
    }
    
    //展开第一个分组
    if ( [self.groups count] > 0 ) {
        for ( FriendGroup* group in groups ) {
            if ( [group.friends count] > 0 ) {
                group.expanded = YES;
                break;
            }
        }
    }
    
    //从服务器上同步联系人数据
    if ( [[GuaziAppDelegate getAppDelegate] isAccountOpened] && networkAvailable ) {
        [self syncUsersFromServer];
    }
    
    self.isLoaded = YES;
}


- (void) sortGroupFriends
{
    for ( FriendGroup* group in groups ) {
        if ( group.groupId == -1 ) continue;
        if ( group.friends == nil || [group.friends count] == 0 ) continue;
        [group.friends sortUsingFunction:sortByScreenName context:nil];
    }
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"通讯录";
	//self.navigationController.navigationBar.tintColor = [UIColor navigationColorForTab:0];
    
	[self buildBarButtonItems];
    [self buildSearchBar];
	
    //如果用户名/密码错误，则打开登录页面
    GuaziAppDelegate* appDelegate = [GuaziAppDelegate getAppDelegate];
    BOOL networkAvailable = [NetworkUtil isbroadbandAvailable];
    if ( networkAvailable ) {
        if ( !appDelegate.isValidateUser ) {
            [GuaziAppDelegate openRegisterView:self];
            return;
        }
    }
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    self.groups = nil;
	self.popoverController = nil;
    self.searchBar = nil;
    self.allUsers = nil;
    self.filterUsers = nil;
    [operationQueue release];
}


- (void)viewWillAppear:(BOOL)animated
{
    if ( !isLoaded ) {
        [self loadData];
    }

    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}




#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ( [self isSearching] ) {
        return 1;
    }
    else {
        NSInteger count = 0;
        for (FriendGroup* group in groups ) {
            if ( group.groupId <= 0 && [group.friends count] == 0 ) continue;
            count++;
        }
        return count;
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ( [self isSearching] ) {
        if ( [filterUsers count] == 0 ) {
            if ( [[self getSearcharText] checkPhone] ) {
                //如果是电话号码，则显示拨打电话、发短信、加入通讯录
                return 3;
            }
            else {
                //如果不是电话号码，则显示加入通讯录
                return 1;
            }
        }
        else {
            if ( [[self getSearcharText] checkPhone] ) {
                //如果是电话号码，则显示拨打电话号码行
                return [filterUsers count] + 1;
            }
            else {
                return [filterUsers count];
            }
        }
    }
    else {
        FriendGroup* group = [self groupForSection:section];
        if ( group == nil ) return 0;
        
        NSInteger rows = 0;
        if ( group.expanded ) {
            rows = [group.friends count];
        }
        
        return rows;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    User* user = nil;
    NSInteger row = indexPath.row;
    NSString* searchText = [self getSearcharText];
    
    if ( [self isSearching] ) {
        if ( [filterUsers count] == 0 ) {
            NSString* s = @"NoContactCell";
            UITableViewCell* noContactCell = [tableView dequeueReusableCellWithIdentifier:s];
            if ( noContactCell == nil ) {
                noContactCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:s];
            }

            if ( [searchText checkPhone] ) {
                //显示3行，拨打电话、发短信、加入联系人
                if ( row == 0 ) {
                    noContactCell.textLabel.text = searchText;
                    noContactCell.imageView.image = [UIImage imageNamed:@"call_contact.png"];
                }
                else if ( row == 1 ) {
                    noContactCell.textLabel.text = @"发短信";
                    noContactCell.imageView.image = [UIImage imageNamed:@"group_sms.png"];
                }
                else {
                    noContactCell.textLabel.text = @"加为联系人";
                    noContactCell.imageView.image = [UIImage imageNamed:@"group_user_add.png"];
                }
            }
            else {
                //显示1行，加入联系人
                noContactCell.textLabel.text = @"加为联系人";
                noContactCell.imageView.image = [UIImage imageNamed:@"group_user_add.png"];
            }
            
            return noContactCell;
        }
        else {
            if ( [searchText checkPhone] ) {
                //显示拨打电话行
                if ( row == 0 ) {
                    NSString* s = @"NoContactCell";
                    UITableViewCell* noContactCell = [tableView dequeueReusableCellWithIdentifier:s];
                    if ( noContactCell == nil ) {
                        noContactCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:s];
                    }
                    noContactCell.textLabel.text = searchText;
                    noContactCell.imageView.image = [UIImage imageNamed:@"call_contact.png"];
                    return noContactCell;
                }
                else {
                    row--;
                }
            }

            user = [filterUsers objectAtIndex:row];
        }
    }
    else {
        FriendGroup* group = [self groupForSection:indexPath.section];
        if ( group == nil ) return nil;
        user = [group.friends objectAtIndex:indexPath.row];
    }

    static NSString *friendsCellId = @"ContactsViewCell";
    ContactCell *cell = (ContactCell*) [tableView dequeueReusableCellWithIdentifier:friendsCellId];
    if (cell == nil) {
        cell = [[[ContactCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:friendsCellId] autorelease];
    }
    
    CGRect frame = CGRectMake(LEFT, 0, CELL_WIDTH, [self getCellHeight:indexPath] - 2 );
    cell.searchText = searchText;
    [cell update:user frame:frame];
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ( [self isSearching] ) {
        if ( [filterUsers count]==0 ) {
            return 50;
        }
        else {
            if ( indexPath.row == 0 ) {
                if ( [[self getSearcharText] checkPhone] ) {
                    return 50;
                }
            }
            return (CGFloat) [self getCellHeight:indexPath];
        }
    }
    else {
        return (CGFloat) [self getCellHeight:indexPath];
    }
}


- (CGFloat) getCellHeight:(NSIndexPath*)indexPath
{
    User* user = nil;
    if ( [self isSearching] ) {
        NSInteger row = indexPath.row;
        if ( [[self getSearcharText] checkPhone] ) row --;
        user = [filterUsers objectAtIndex:row];
    }
    else {
        FriendGroup* group = [self groupForSection:indexPath.section];
        user = [group.friends objectAtIndex:indexPath.row];
    }
    
	CGFloat height = [ContactCell getCellHeight:user isSearching:[self isSearching]];
    return height;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	return 30;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if ( ![self isSearching] ) {
        FriendGroup* group = [self groupForSection:section];
        
        CGRect frame = CGRectMake(0, 0, 320, 30);
        GroupHeaderView* headerView = [[[GroupHeaderView alloc] initWithFrame:frame group:group section:section] autorelease];
        
        return (UIView*) headerView;
    }
    else {
        return nil;
    }
}


- (FriendGroup*) groupForSection:(NSInteger)section
{
    NSInteger index = -1;
    for ( FriendGroup* group in groups ) {
        if ( group.groupId <= 0 && [group.friends count] == 0 ) continue;
        index++;
        if ( index == section ) return group;
    }
    
    return nil;
}


- (NSInteger) sectionForGroup:(sqlite_int64)groupId
{
    NSInteger index = -1;
    for ( FriendGroup* g in groups ) {
        if ( g.groupId <=0 && [g.friends count] == 0 ) continue;
        index++;
        if ( groupId == g.groupId ) {
            return index;
        }
    }
    
    return -1;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

/*
- (NSIndexPath*) tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ( [self isSearching] ) {
        if ( [filterUsers count]==0 ) return nil;
        if ( indexPath.row == 0 ) return nil;
        return indexPath;
    }
    else {
        return indexPath;
    }
}
*/

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    User* user = nil;
    if ( [self isSearching] ) {
        NSString* searchText = [self getSearcharText];
        if ( [filterUsers count] == 0 ) {
            if ( [searchText checkPhone] ) {
                if ( indexPath.row == 0 ) {
                    //拨打电话
                    [self callPhone:searchText];
                }
                else if ( indexPath.row == 1 ) {
                    //发短信
                    [self sendMessage:searchText];
                }
                else {
                   //加为联系人
                    [self addContact:searchText];
                }
            }
            else {
                //加为联系人
                [self addContact:searchText];
            }
            return;
        }
        else {
            if ( indexPath.row == 0 ) {
                //拨打电话
                [self callPhone:searchText];
                return;
            }
            else {
                //人员信息
                user = [filterUsers objectAtIndex:indexPath.row - 1];
            }
        }
    }
    else {
        FriendGroup* group = [self groupForSection:indexPath.section];
        if ( group == nil ) return;
        user = [group.friends objectAtIndex:indexPath.row];
    }
    
    //ProfileViewController* controller = [[ProfileViewController alloc] initWithProfile:user];
    FriendDetailViewController* controller = [[FriendDetailViewController alloc] initWithUser:user];
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
}


#pragma mark - search bar delegate & other methods

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"remarkName contains[cd] %@ or phone contains[cd] %@", [searchText trim], [searchText trim]];
    self.filterUsers = [allUsers filteredArrayUsingPredicate:predicate];
    
    [self buildBarButtonItems];
    [self.tableView reloadData];
}


- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self.searchBar resignFirstResponder];
}


- (NSString*) getSearcharText
{
    NSString* s = [searchBar.text trim];
    return s;
}


- (BOOL) isSearching
{
    NSString* s = [self getSearcharText];
    if ( s && [s length]>0 ) {
        return YES;
    }
    else {
        return NO;
    }
}


#pragma mark - section index

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)aTableView 
{
    NSMutableDictionary* dic = [NSMutableDictionary dictionary];
    
    if ( ![self isSearching] ) {
        FriendGroup* group = [self findExpandedGroup];
        if ( group == nil ) return nil;
        if ( group.groupId == -1 ) return nil;
        
        for ( User* user in group.friends ) {
            NSString* py = user.pyLetters;
            if ( !py || [py length] == 0 ) continue;
            NSString* s = [py substringToIndex:1];
            if ( [dic objectForKey:s] == nil ) {
                [dic setObject:s forKey:s];
            }
        }
    }
    
    NSArray* sortedArray = [[dic allValues] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    if ( [sortedArray count] > 5 ) {
        return sortedArray;
    }
    else {
        return nil;
    }
}


- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    if ( ![self isSearching] ) {
        FriendGroup* group = [self findExpandedGroup];
        if ( group == nil ) return -1;
        
        NSInteger row = -1;
        for ( int i=0; i<[group.friends count]; i++ ) {
            User* user = [group.friends objectAtIndex:i];
            NSString* py = user.pyLetters;
            if ( !py || [py length]==0 ) continue;
            
            
            if ( [title compare:py]!=NSOrderedDescending ) {
                row = i;
                break;
            }
        }
        
        if ( index >= 0 ) {
            NSInteger section = [self sectionForGroup:group.groupId];
            [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:section] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
    }
	return -1;
}


@end
